package com.yitiao.multithread.completablefuture;

import lombok.Data;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

public class MyCompletableFuture {

    static List<Mall> list = Arrays.asList(
            new Mall("jd "),
            new Mall("pdd "),
            new Mall("tb ")
    );

    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        extracted();
        /**
         * 案例：电商比价- 淘宝上各商家卖同一本书，多少钱
         * A:一个个的问
         * B:广播通知
         *
         * 对于复杂查询，大量的set
         */
        String goods = "mysql";
        List<String> list1 = list.stream().map(mall -> mall.getName() + mall.calcPrice(goods)).collect(Collectors.toList());

        System.out.println(list1);

        List<String> list2 = list.stream().map(mall ->
                CompletableFuture.supplyAsync(
                        () -> mall.getName() + mall.calcPrice(goods), Executors.newFixedThreadPool(8))).collect(Collectors.toList())
                .stream().map(CompletableFuture::join).collect(Collectors.toList());
        System.out.println(list2);
        // 对计算结果的处理、消费、合并、
//        thenApply handle  ASYC 用新的线程异步执行

    }

    @Data
    static class Mall {
        public String name;

        public Mall(String name) {
            this.name = name;
        }

        public double calcPrice(String name) {
            return ThreadLocalRandom.current().nextDouble() * 2 + name.charAt(0);
        }
    }

    private static void extracted() throws InterruptedException, ExecutionException {
        CompletableFuture.supplyAsync(() -> {
            // 异常处理
            int a = 10 / 0;
            return "1";
        }).whenComplete((v, e) -> {
            // 如果没有异常
            if (e == null) {
                System.out.println("-----res:" + v);
            }
        }).exceptionally(e -> {
            // 返回异常信息
            System.out.println(e.toString());
            return e.toString();
        }).get();
        // get join都可 join不需要抛出异常。
    }
}
